<?php

namespace Biz\service;

use Biz\cache\Activitys as cActivitys;
use Biz\model\activity\LimitTimeRobbing;
use Biz\model\activity\LimitTimeRobbingSku as mLimitTimeRobbingSku;
use Biz\model\GoodsBasicInfo;
use Biz\model\GoodsSku;
use Biz\model\ShippingTempl;
use Biz\model\ShippingTemplAttr;
use Biz\service\trade\UserAddress;
use Biz\module\Behaviors\ActivityBehavior;
use Biz\tools\ShopArea;
use Doraemon\tools\HhzClient;
use Biz\pockets\constInterface\ActivityInfo as constActivityInfo;
use Biz\model\trade\OrderActivityLog;
use Biz\service\activity\FlashSale;
use Biz\module\Behaviors\Activity\FullShipping;
/**
 * @deprecated
 */
class Activitys
{


    const ICON_DISCOUNT_URL = "http://img.hhz1.cn/Op-imageShow/31c71303u02000000p5vtwv?iv=1"; //优惠

    const ICON_SHIPPING_FREE = "http://img.hhz1.cn/Op-imageShow/d73a2302o01000000pa1v9r?iv=1"; //包邮

    const ICON_FULL_SHIPPING = 'http://img.hhz1.cn/Op-imageShow/6fe03302o01000000p9skvf?iv=1'; // 满包邮

    const ICON_LIMIT_TIME_ROBBING = "http://img.hhz1.cn/Op-imageShow/b0b9e302o01000000p9skvf?iv=1"; //限时抢

    const ICON_NEW_GOODS = 'http://img.hhz1.cn/Op-imageShow/e98db302o01000000p9skvf?iv=1'; //新品

    const LIMIT_TIME_PAGE_COVER_IMG = "http://img.hhz1.cn/Op-imageShow/f986820ku09g0Qr00pijksd?iv=1";

    const NEW_GOODS_CONDITION = '-7 days';


    const ACTIVI_ICON_MAP = [
        constActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB => self::ICON_LIMIT_TIME_ROBBING,
        constActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING => self::ICON_FULL_SHIPPING,
        constActivityInfo::ACTIVITY_TYPE_ADDRESS_FREE => self::ICON_SHIPPING_FREE,
        constActivityInfo::ACTIVITY_TYPE_NEW => self::ICON_NEW_GOODS
    ];

    /**
     * 通过sku_ids获得正在进行中的限时抢活动
     *
     * @param $skuIds
     * @return array
     */
    public static function getLimitTimeRobbBySkuIds($skuIds)
    {
        //限时抢
        $limitTimeRobbings = mLimitTimeRobbingSku::getInfoBySkuIds($skuIds, [
            "start_time[<]" => date('Y-m-d H:i:s'),
            "end_time[>]" => date('Y-m-d H:i:s'),
            "promo_stock[>]" => 0,
            "status" => mLimitTimeRobbingSku::STATUS_NORMAL
        ]);


        $limitTimeRobbings = array_map(function ($limitTimeRobbing) {
            $limitTimeRobbing['type_id'] = constActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB;
            $limitTimeRobbing['title'] = constActivityInfo::ACTIVITY_TYPES_MAPS[constActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB];
            return $limitTimeRobbing;
        }, $limitTimeRobbings);


        return array_column($limitTimeRobbings, null, 'sku_id');

    }

    /**
     * 限时抢 正在进行中的商品ids
     * @param array $goods_ids
     * @return array $ids
     */
    public static function getCurrentLimitRobByGids(array $goodsIds)
    {
        $ids = [];
		$flashSaleList = FlashSale::getCacheFlashSale();
		foreach ($flashSaleList as $flashId =>  $flashInfo) {
			if ($flashInfo['start_time'] < date('Y-m-d H:i:s') && $flashInfo['end_time'] > date('Y-m-d H:i:s')) {
				foreach ($flashInfo['goods'] as $goodsId => $good) {
					if (in_array($goodsId, $goodsIds)) {
						$ids[] = $goodsId;
					}
				}
			}
		}
		$goodsInfos = Goods::Goods($ids, Goods::FIELDS_GROUP_LIST, ['activity_type' => constActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB]);
		$ids = [];
		foreach ($goodsInfos as $goodsInfo) {
			if ($goodsInfo['activity_stock']) {
				$ids[] = $goodsInfo['id'];
			}
		}
        return $ids;
    }

    public static function getCurrentLimitRobBySkuIds(array $skuIds)
    {
        $ids = [];
		$flashSaleList = FlashSale::getCacheFlashSale();
		foreach ($flashSaleList as $flashId =>  $flashInfo) {
			if ($flashInfo['start_time'] < date('Y-m-d H:i:s') && $flashInfo['end_time'] > date('Y-m-d H:i:s')) {
				foreach ($flashInfo['goods'] as $goodsId => $good) {
					foreach ($good['skus'] as $sku) {
						if (in_array($sku['sku_id'], $skuIds)) {
							$ids[] = $sku['sku_id'];
						}
					}
				}
			}
		}
		$skuInfos = Sku::Sku4Order($ids);
		$ids = [];
		foreach ($skuInfos as $skuInfo) {
			if ($skuInfo['activity_type'] == constActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB && $skuInfo['actual_stock']) {
				$ids[] = $skuInfo['sku_id'];
			}
		}
        return $ids;
    }

    /**
     * 获得商品的限时抢活动信息 读取缓存
     *
     * @param $goodsIds
     * @param $idx 场次默认为商品的第一场
     * @return array
     *
     */
    public static function getLimitTimeRobbingByGids($goodsIds, $idx = 0)
    {
        list($noCacheGoodIds, $RobbingInfos) = cActivitys::getMultiRobbing((array)$goodsIds, $idx);
        $returnRst = [];
        foreach ($RobbingInfos as $goods_id => $robbingInfo) {

            $returnRst[$goods_id]['id'] = $robbingInfo['id'];
            $returnRst[$goods_id]['type_id'] = constActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB;
            $returnRst[$goods_id]['title'] = constActivityInfo::ACTIVITY_TYPES_MAPS[constActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB];
            $returnRst[$goods_id]['icon'] = self::ICON_LIMIT_TIME_ROBBING;
            $returnRst[$goods_id]['params'] = [
                "sys_time" => time(),
                "begin_time" => strtotime($robbingInfo["start_time"]),
                "end_time" => strtotime($robbingInfo["end_time"]),
                "min_price" => $robbingInfo['buy_price'],
                "max_price" => $robbingInfo['buy_price'],
            ];
        }

        return $returnRst;

    }

    public static function AddressFree($shippingTemplIds, $areaCode, $icon_url = self::ICON_SHIPPING_FREE)
    {

        $templInfos = ShippingTempl::getTemplinfos($shippingTemplIds);
        $defaultCityCode = UserAddress::getUserDefaultCityCode(HhzClient::getUid());
        $defaultProvinceCode = '';
        if ($defaultCityCode) {
            $defaultAreaCodeArr = ShopArea::getAreaCodeArr($defaultCityCode);
            $defaultProvinceCode = $defaultAreaCodeArr[0];
        }

        if ($areaCode == $defaultCityCode) {
            $areaCode = $defaultCityCode;
        } else if ($areaCode == $defaultProvinceCode) {
            $areaCode = $defaultProvinceCode;
        }
        $addressFrees = array_map(function ($templInfo) use ($areaCode, $icon_url) {
            $areaCodeArr = ShopArea::getAreaCodeArr($areaCode);
            $provinceId = $areaCodeArr[0];
            $cityId = $areaCodeArr[1];
            if ($provinceId || $cityId) {
                foreach ($templInfo['list'] as $shippingTemplAttr) {
                    $area = explode(',', $shippingTemplAttr['area']);
                    if ($shippingTemplAttr['type'] == ShippingTemplAttr::TYPE_FREE) {
                        if (in_array($provinceId, $area) || in_array($cityId, $area)) {
                            return [
                                "id" => $shippingTemplAttr['id'],
                                "type_id" => constActivityInfo::ACTIVITY_TYPE_ADDRESS_FREE,
                                "title" => $templInfo['name'],
                                "desc" => $templInfo['name'] . "  " . str_replace(" ", "、", $shippingTemplAttr['area_str']),
                                "icon" => $icon_url,
                                "params" => null
                            ];
                        }
                    }
                }
            }

            return null;

        }, $templInfos);

        $addressFrees = array_filter($addressFrees);
        $shippingTemplIds = array_diff($shippingTemplIds, array_keys($addressFrees));
        foreach ($shippingTemplIds as $shippingTemplId) {
            $defaultPrice = ShippingTemplAttr::getDefaultPrice($shippingTemplId);
            if ($defaultPrice == "0.00") {
                $addressFrees[$shippingTemplId] = [
                    "id" => $shippingTemplId,
                    "type_id" => constActivityInfo::ACTIVITY_TYPE_ADDRESS_FREE,
                    "title" => $templInfos[$shippingTemplId]['name'],
                    "desc" => $templInfos[$shippingTemplId]['name'],
                    "icon" => $icon_url,
                    "params" => null
                ];
            }
        }
        return array_filter($addressFrees);
    }


    public static function NewGoods($goods_ids, $icon_url = self::ICON_NEW_GOODS)
    {
        $now_date = date("Y-m-d", strtotime("-7 days"));
        $goodsInfos = GoodsBasicInfo::getInfos([
            'goods_id' => $goods_ids,
            'first_online_time[>]' => $now_date,
            'status' => [GoodsBasicInfo::STATUS_PASSED, GoodsBasicInfo::STATUS_ONLINE]
        ]);


        $goodsInfos = array_column($goodsInfos, null, 'goods_id');
        return array_map(function ($goodsInfo) use ($icon_url) {
            return [
                'id' => $goodsInfo['goods_id'],
                'type_id' => constActivityInfo::ACTIVITY_TYPE_NEW,
                'tile' => constActivityInfo::ACTIVITY_TYPES_MAPS[constActivityInfo::ACTIVITY_TYPE_NEW],
                'desc' => constActivityInfo::ACTIVITY_TYPES_MAPS[constActivityInfo::ACTIVITY_TYPE_NEW],
                'icon' => $icon_url,
                "params" => null
            ];
        }, $goodsInfos);
    }

    public static function additionalShippingFree($goodsInfo)
    {
        if ($goodsInfo['shipping_info']['price'] == 0) {
            return [
                "id" => "",
                "type_id" => constActivityInfo::ACTIVITY_TYPE_ADDRESS_FREE,
                "title" => "",
                "desc" => "",
                "icon" => self::ICON_SHIPPING_FREE,
                "params" => null
            ];
        } else {
            return false;
        }
    }

    public static function additionalNewGoods($goodsInfo, $icon_url = self::ICON_NEW_GOODS)
    {
        $newGoodsdate = date("Y-m-d H:i:s", strtotime(self::NEW_GOODS_CONDITION));
        if ($goodsInfo['operate_time'] > $newGoodsdate) {
            return [
                'id' => $goodsInfo['goods_id'],
                'type_id' => constActivityInfo::ACTIVITY_TYPE_NEW,
                'tile' => constActivityInfo::ACTIVITY_TYPES_MAPS[constActivityInfo::ACTIVITY_TYPE_NEW],
                'desc' => constActivityInfo::ACTIVITY_TYPES_MAPS[constActivityInfo::ACTIVITY_TYPE_NEW],
                'icon' => $icon_url,
                "params" => null
            ];
        } else {
            return false;
        }
    }


    /**
     * @param array $logsInfo
     * [[ 'order_no' 'activity_id' 'activity_type' 'sku_id' 'origin_price' 'purchase_price']]
     */

    public static function addLog(array $logsInfo = [])
    {
        foreach ($logsInfo as $logInfo) {
            if (!in_array(
                $logInfo['activity_type'],
                array_keys(
                    constActivityInfo::ACTIVITY_TYPES_MAPS
                )
            )) {

                throw new \Exception('不存在的活动类型');
            }
        }

        return OrderActivityLog::addLog($logsInfo);

    }

    public static function LimitTimeRobHappening($now_date = '')
    {
        if (!$now_date) {
            $now_date = date("Y-m-d H:i:s");
        }
        $lists = LimitTimeRobbing::HappeningList($now_date);

        $ordermap = array_column($lists, 'order', 'goods_id');

        $goodsIds = array_keys($lists);
        $goodsInfos = GoodsDetail::GoodsInfoList($goodsIds);
        $robInfos = self::getLimitTimeRobbingByGids($goodsIds);

        $priceRange = ShopMall::InLimitTimeSkuPrice($goodsIds, $now_date);

        $rst = [
            'cover_img' => self::LIMIT_TIME_PAGE_COVER_IMG,
            'time_down' => null,
            'goods_list' => []
        ];

        array_multisort($ordermap, $goodsInfos);

        foreach ($goodsInfos as $goodsInfo) {
            if (!$rst['time_down']) {
                $rst['time_down'] = (object)[
                    "sys_time" => time(),
                    "begin_time" => $goodsInfo['active_top']['params']['begin_time'],
                    "end_time" => $goodsInfo['active_top']['params']['end_time'],
                ];
            }
            $goods_id = $goodsInfo['goods_id'];

            if ($goodsInfo['app_status'] == GoodsBasicInfo::STATUS_APP_NOMAL) {
                $rst['goods_list'][] = [
                    'id' => $goodsInfo['goods_id'],
                    'title' => $goodsInfo['title'],
                    'describe' => $lists[$goods_id]['describe'],
                    'min_price' => isset($priceRange[$goods_id][0]) ? $priceRange[$goods_id][0] : $goodsInfo['min_price'],
                    'max_price' => isset($priceRange[$goods_id][1]) ? $priceRange[$goods_id][1] : $goodsInfo['max_price'],
                    'cover_img' => $goodsInfo['spec_img_url'],
                    'status' => $goodsInfo['app_status'],
                    'active_top' => [
                        'id' => $goodsInfo['active_top']['id'],
                        'type_id' => $goodsInfo['active_top']['type_id'],
                        'title' => $goodsInfo['active_top']['title'],
                        'params' => [
                            "sys_time" => time(),
                            "begin_time" => $goodsInfo['active_top']['params']['begin_time'],
                            "end_time" => $goodsInfo['active_top']['params']['end_time'],
                            "stock" => mLimitTimeRobbingSku::getStockByRobid($lists[$goods_id]['id']),
                            "min_price" => $robInfos[$goods_id]['params']['min_price'],
                            "max_price" => $robInfos[$goods_id]['params']['max_price'],
                        ],
                    ]
                ];
            }

        }

        $has_stock = [];
        $no_stock = [];
        foreach ($rst['goods_list'] as $goodslist) {
            if ($goodslist['active_top']['params']['stock']) {
                $has_stock[] = $goodslist;
            } else {
                $no_stock[] = $goodslist;
            }
        }
        $rst['goods_list'] = array_merge($has_stock, $no_stock);

        return $rst;
    }

    public static function LimitTimeRobTrait()
    {
        $lists = LimitTimeRobbing::TraitList();
        if ($lists) {
            $start_time = $lists[0]['start_time'];
            $end_time = $lists[0]['end_time'];

            $time = abs((strtotime($start_time) + strtotime($end_time)) / 2);

            $limitRobInfos = self::LimitTimeRobHappening(date("Y-m-d H:i:s", $time));

            foreach ($limitRobInfos['goods_list'] as &$limitRobInfo) {
                $limitRobInfo['active_top'] = Activitys::getLimitTimeRobbingByGids([$limitRobInfo['id']],
                    1)[$limitRobInfo['id']];
            }

            return $limitRobInfos;
        }

        return [
            'cover_img' => self::LIMIT_TIME_PAGE_COVER_IMG,
            'time_down' => (object)[],
            'goods_list' => []
        ];

    }

    public static function addActivityInfo($type_id, $shop_id, array $fileds)
    {
        ActivityBehavior::add($shop_id, $type_id, $fileds);

        self::updateCache($type_id, $shop_id);
    }

    public static function ActivityList($shop_id, $type_id = constActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING)
    {

        return ActivityBehavior::ActivityList($type_id, $shop_id);
    }

    public static function Edit($shop_id, $id, $type_id, $fields)
    {
        ActivityBehavior::EditActivitys($type_id, $shop_id, $id, $fields);

        self::updateCache($type_id, $shop_id);

    }

    public static function Info($type_id, $id, $shop_id)
    {
        return ActivityBehavior::Info($shop_id, $id, $type_id);
    }

    public static function changeStatus($shop_id, $id, $type_id)
    {
        $result = ActivityBehavior::changeStatus($shop_id, $id, $type_id);

        self::updateCache($type_id, $shop_id);
        return $result;
    }

    private static function updateCache($type_id, $shop_id)
    {

    }

}
